from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import Serializer

from oauth.models import OAuthQQUser
from oauth.utils import check_openid
from users.models import User


class QQUserSerializer(Serializer):
    #绑定openid和美多用户的序列化器


    openid = serializers.CharField(label='openid',write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$',write_only=True)
    password = serializers.CharField(label='密码', max_length=20, min_length=8,write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)

    def validate(self, attrs):
        encrypted_openid = attrs.get('openid') #加密后的openid
        print(encrypted_openid)
        openid = check_openid(encrypted_openid)
        print(openid)
        if not openid:
            raise ValidationError({"message":"openid无效"})
        #修改字典中的openid
        attrs['openid'] = openid


        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        password = attrs.get('password')


        #校验短信验证码
        redis_conn = get_redis_connection('sms_codes')  #StrictRedis
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if not real_sms_code:
            raise serializers.ValidationError({'message':'短信验证码无效'})
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError({'message':'短信验证码错误'})
        #查询要绑定的美多用户对象
        try:
            user = User.objects.get(mobile=mobile)

        except:
            #如果美多用户不存在,需要先以手机号作为用户名,创建出美多用户
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile
            )

        else:
            # 如果美多用户存在,校验密码是否正确
            if not user.check_password(password):
                raise ValidationError({'message': '要绑定的用户密码不正确'})


        #往字典中新增用户对象,以便于后续的保存操作
        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        #绑定openid和美多用户(往映射表添加一条微信)
        openid = validated_data.get('openid')
        user = validated_data.get('user')

        #添加一条数据到映射表中
        OAuthQQUser.objects.create(
            openid = openid,
            user = user
        )

        return user  #绑定的美多用户对象

